import { Component, Key, createRef } from "react";
import { Avatar, Button, Space, Table, TableColumnsType, message } from "antd";
import { addUser, deleteUser, getUserPage, updateUser } from "@/api/user";
import UpsertModal from "./components/upsert-modal";

interface IProps {}
interface IState {
  list: User.Info[];
  total: number;
  loading: boolean;
  checkedIds: Key[];
}

export default class User extends Component<IProps, IState> {
  upRef = createRef<UpsertModal>();

  columns: TableColumnsType<User.Info> = [
    { title: "Id", dataIndex: "id" },
    {
      title: "头像",
      dataIndex: "headImg",
      render: (_, record) => <Avatar src={record.headImg} />,
    },
    { title: "用户名", dataIndex: "username" },
    { title: "姓名", dataIndex: "name" },
    { title: "昵称", dataIndex: "nickName" },
    { title: "角色", dataIndex: "roleName" },
    { title: "状态", dataIndex: "status" },
    {
      title: "操作",
      render: (_, record) => (
        <Space>
          <Button
            type="primary"
            size="small"
            onClick={() => this.upRef.current?.open(record)}
          >
            编辑
          </Button>
        </Space>
      ),
    },
  ];

  page = 1; // 页码
  size = 15; // 每页显示条数

  state: Readonly<IState> = {
    list: [],
    total: 1, // 总的数据条数
    loading: false,
    checkedIds: [],
  };

  /**
   * 刷新数据
   */
  refresh = () => {
    const { page, size } = this;
    this.setState({ loading: true });
    getUserPage({ page, size }).then((resp) => {
      this.setState({
        list: resp.list,
        total: resp.pagination.total,
        loading: false,
      });
    });
  };

  changeSelection = (checkedIds: Key[]) => {
    this.setState({ checkedIds });
  };

  changePagination = (page: number, pageSize: number) => {
    console.log("changePagination", page, pageSize);
    // 修改数据
    this.page = page;
    this.size = pageSize;
    // 重新 refresh
    this.refresh();
  };

  handleDelete = async (ids: Key[]) => {
    await deleteUser({ ids });
    message.success("删除成功");
    this.refresh();
  };

  handleOk = async (params: any) => {
    console.log("handleOk", params);
    // 根据 params 中是否有 id 来控制调用不同的接口
    if (params.id) {
      await updateUser(params);
      message.success("编辑成功");
    } else {
      await addUser(params);
      message.success("新增成功");
    }
    // 关闭弹窗
    this.upRef.current?.close();
    // 刷新数据‘
    this.refresh();
  };

  render() {
    console.log("render");
    return (
      <Space direction="vertical" style={{ display: "flex" }}>
        <h2>用户列表</h2>

        <Space>
          <Button type="primary" onClick={() => this.upRef.current?.open()}>
            新增
          </Button>
          <Button
            type="primary"
            danger
            disabled={this.state.checkedIds.length <= 0}
            onClick={() => this.handleDelete(this.state.checkedIds)}
          >
            删除
          </Button>
        </Space>

        <Table
          bordered
          size="small"
          rowKey="id"
          loading={this.state.loading}
          columns={this.columns}
          dataSource={this.state.list}
          rowSelection={{
            onChange: this.changeSelection,
          }}
          pagination={{
            pageSize: this.size,
            total: this.state.total,
            onChange: this.changePagination,
          }}
        />

        <UpsertModal ref={this.upRef} onOk={this.handleOk} />
      </Space>
    );
  }

  componentDidMount(): void {
    this.refresh();
  }
}
